package com.hmdp;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@SpringBootTest
public class RedissonTest2 {

    public static void main(String[] args) {
        System.out.println("if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                "return 1; " +
                "end; " +
                "return 0;");
    }

    @Resource
    private RedissonClient redissonClient;

    private RLock lock;

    @BeforeEach
    void setUp() {
        lock = redissonClient.getLock("order");
    }

    @Test
    void method1() throws InterruptedException {
        boolean isLocked = lock.tryLock(1L, TimeUnit.SECONDS);
        if (!isLocked) {
            log.error("获取锁失败===>1");
            return;
        }
        try {
            log.error("获取锁成功===>1");
            method2();
        } finally {
            log.error("准备释放锁===>1");
            lock.unlock();
        }
    }

    @Test
    void method2() throws InterruptedException {
        boolean isLocked = lock.tryLock();
        if (!isLocked) {
            log.error("获取锁失败===>2");
            return;
        }
        try {
            log.error("获取锁成功===>2");
        } finally {
            log.error("准备释放锁===>2");
            lock.unlock();
        }
    }
}

